use actix_web::{HttpRequest, HttpResponse, web};

use common::ctx::get_dict_by_group_code;
use common::error::MyError;
use common::header::Authorization;
use common::r::JsonResult;
use entity::{sys_dict, sys_dict_group};
use model::dict::{CreateDict, CreateDictGroup, DictGroupPage, DictPage};
use service::base::BaseService;
use service::dict::{DictGroupService, DictService};
use service::manager::dict::DictManager;
use service::manager::dict_group::DictGroupManager;

use crate::controller::base::BaseController;

pub struct DictGroupController {}

impl
    BaseController<
        DictGroupService,
        i64,
        sys_dict_group::Model,
        DictGroupPage,
        CreateDictGroup,
        sys_dict_group::Model,
        DictGroupManager,
    > for DictGroupController
{
}

impl DictGroupController {
    pub async fn search_list(form: web::Json<DictGroupPage>) -> Result<HttpResponse, MyError> {
        let res = DictGroupService::search_list(form.into_inner()).await?;
        Ok(HttpResponse::Ok().json(JsonResult::ok(res)))
    }
    pub async fn get_dict_list_by_code(code: web::Path<String>) -> Result<HttpResponse, MyError> {
        let code = code.into_inner();
        Ok(HttpResponse::Ok().json(JsonResult::ok(get_dict_by_group_code(&code)?)))
    }
    pub async fn get_dict_list_by_id(
        id: web::Path<i64>,
        req: HttpRequest,
        authorization: web::Header<Authorization>,
    ) -> Result<HttpResponse, MyError> {
        let group = DictGroupService::info(id.into_inner(), &req, authorization).await?;
        Ok(
            HttpResponse::Ok().json(JsonResult::ok(get_dict_by_group_code(
                &group.group_code.unwrap(),
            )?)),
        )
    }
}

pub struct DictController {}
impl
    BaseController<
        DictService,
        i64,
        sys_dict::Model,
        DictPage,
        CreateDict,
        sys_dict::Model,
        DictManager,
    > for DictController
{
}
